package com.zr.redis.service;


import com.zr.redis.util.DistributedLockUtil;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LockExampleService {

    private final DistributedLockUtil distributedLockUtil;

    @Autowired
    public LockExampleService(DistributedLockUtil distributedLockUtil) {
        this.distributedLockUtil = distributedLockUtil;
    }

    /**
     * 示例1：使用 lock() 和 unlock() 方法
     */
    public void doWithLock() {
        String lockKey = "example:lock:key1";
        RLock lock = null;
        try {
            // 获取锁
            lock = distributedLockUtil.lock(lockKey, 5, TimeUnit.SECONDS);

            // 执行需要加锁的业务逻辑
            System.out.println("执行加锁的业务逻辑...");
            // 模拟业务处理时间
            Thread.sleep(2000);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("处理被中断", e);
        } finally {
            // 释放锁
            distributedLockUtil.unlock(lock);
        }
    }

    /**
     * 示例2：使用 tryLock() 方法
     */
    public void doWithTryLock() {
        String lockKey = "example:lock:key2";
        try {
            // 尝试获取锁，最多等待3秒，上锁后5秒自动释放
            boolean locked = distributedLockUtil.tryLock(lockKey, 3, 5, TimeUnit.SECONDS);
            if (locked) {
                try {
                    // 执行需要加锁的业务逻辑
                    System.out.println("成功获取锁，执行业务逻辑...");
                    // 模拟业务处理时间
                    Thread.sleep(2000);
                } finally {
                    // 释放锁
                    distributedLockUtil.unlock(lockKey);
                }
            } else {
                // 获取锁失败，处理逻辑
                System.out.println("获取锁失败，无法执行业务逻辑");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("处理被中断", e);
        }
    }
}

